import 'package:agora_rtc_engine/rtc_engine.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:star_author/widgets/base_widget/app_bar/custom_app_bar_simple.dart';

import '../../../utils/utils.dart';

class LiveDetectionInfo extends StatefulWidget {
  late final RtcEngine? engine;
  static LocalVideoStats? stats = null;

  LiveDetectionInfo({
    Key? key,
    this.engine,
  }) : super(key: key);

  @override
  State<LiveDetectionInfo> createState() => _LiveDetectionInfoState();
}

class _LiveDetectionInfoState extends State<LiveDetectionInfo> {
  List data = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if (LiveDetectionInfo.stats != null) {
      data.addAll([
        {
          "title": "实际发送码率 (Kbps)",
          "value": "${LiveDetectionInfo.stats?.sentBitrate ?? 0}Kbps",
        },
        {
          "title": "实际发送帧率 (fps)",
          "value": "${LiveDetectionInfo.stats?.sentFrameRate ?? 0}fps",
        },
        {
          "title": "本地视频编码器的输出帧率 (fps)",
          "value": "${LiveDetectionInfo.stats?.encoderOutputFrameRate ?? 0}fps",
        },
        {
          "title": "本地视频采集帧率 (fps)",
          "value": "${LiveDetectionInfo.stats?.captureFrameRate ?? 0}fps",
        },
        {
          "title": "本地视频渲染器的输出帧率 (fps)",
          "value":
              "${LiveDetectionInfo.stats?.rendererOutputFrameRate ?? 0}fps",
        },
        {
          "title": "当前编码器的目标编码码率 (Kbps)",
          "value": "${LiveDetectionInfo.stats?.targetBitrate ?? 0}Kbps",
        },
        {
          "title": "视频编码码率（Kbps）",
          "value": "${LiveDetectionInfo.stats?.encodedBitrate ?? 0}Kbps",
        },
        {
          "title": "当前编码器的目标编码帧率 (fps)",
          "value": "${LiveDetectionInfo.stats?.targetFrameRate ?? 0}fps",
        },
        {
          "title": "视频编码宽度（px）",
          "value": "${LiveDetectionInfo.stats?.encodedFrameWidth ?? 0}px",
        },
        {
          "title": "视频编码高度（px）",
          "value": "${LiveDetectionInfo.stats?.encodedFrameHeight ?? 0}px",
        },
        {
          "title": "弱网对抗前本端到声网边缘\n服务器的视频丢包率 (%)",
          "value": "${LiveDetectionInfo.stats?.txPacketLossRate ?? 0}%",
        },
        {
          "title": "本地视频质量",
          "value":
              "${buildMap[LiveDetectionInfo.stats?.qualityAdaptIndication]}",
        },
        {
          "title": "本地采集的画质亮度级别",
          "value":
              "${buildMap2[LiveDetectionInfo.stats?.captureBrightnessLevel ?? CaptureBrightnessLevelType.Invalid]}",
        },
        {
          "title": "视频的编码类型",
          "value": "${buildMap3[LiveDetectionInfo.stats?.codecType]}",
        },
        {
          "title": "视频发送的帧数，累计值",
          "value": "${LiveDetectionInfo.stats?.encodedFrameCount}",
        },
      ]);
    } else {
      data.add(
        {
          "title": "监控信息",
          "value": "获取信息中,请过几秒打开页面查看",
        },
      );
    }

    widget.engine?.getConnectionState().then((value) {
      setState(() {
        connectionStateType = value;
      });
    });
  }

  ConnectionStateType? connectionStateType = null;

  Map buildMap = {
    VideoQualityAdaptIndication.AdaptNone: "本地视频质量不变",
    VideoQualityAdaptIndication.AdaptUpBandwidth: "因网络带宽增加，本地视频质量改善",
    VideoQualityAdaptIndication.AdaptDownBandwidth: "因网络带宽减少，本地视频质量变差",
  };
  Map buildMap2 = {
    CaptureBrightnessLevelType.Invalid: "请等待几秒",
    CaptureBrightnessLevelType.Normal: "本地采集的画质亮度正常",
    CaptureBrightnessLevelType.Bright: "本地采集的画质亮度偏亮",
    CaptureBrightnessLevelType.Dark: "本地采集的画质亮度偏暗",
  };
  Map buildMap3 = {
    VideoCodecType.VP8: "标准 VP8",
    VideoCodecType.H264: "标准 H.264",
    VideoCodecType.EVP: "增强 VP8",
    VideoCodecType.E264: "增强 H.264",
  };

  Map connect_map = {
    ConnectionStateType.Failed: " 网络连接断开",
    ConnectionStateType.Connecting: " 建立网络连接中",
    ConnectionStateType.Disconnected: " 网络连接断开",
    ConnectionStateType.Connected: " 网络已连接",
    ConnectionStateType.Reconnecting: " 重新建立网络连接中",
  };

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBarSimple("直播监测信息"),
      body: Container(
        width: Get.width,
        color: Colors.white,
        child: Container(
          child: Builder(
            builder: (context) {
              return ListView(
                shrinkWrap: true,
                children: [
                  Container(
                    padding: EdgeInsets.symmetric(
                      vertical: 20.w,
                    ),
                    alignment: Alignment.center,
                    child: Text(
                        "当前连接状态:${connect_map[connectionStateType ?? ConnectionStateType.Failed]}"),
                  ),
                  separator(),
                  ListView.separated(
                    shrinkWrap: true,
                    physics: NeverScrollableScrollPhysics(),
                    itemBuilder: (context, index) {
                      return buildRow(
                          data[index]['title'], data[index]['value']);
                    },
                    itemCount: data.length,
                    padding: EdgeInsets.zero,
                    separatorBuilder: (context, index) => separator(),
                  ),
                  SizedBox(
                    height: 30.w,
                  ),
                ],
              );
            },
          ),
        ),
      ),
    );
  }

  separator() {
    return Container(
      child: Divider(
        height: 1,
        color: rgba(238, 238, 238, 1),
      ),
      margin: EdgeInsets.symmetric(
        horizontal: 12.w,
      ),
    );
  }

  buildRow(title, value) {
    return Container(
      padding: EdgeInsets.symmetric(
        horizontal: 12.w,
        vertical: 20.w,
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Container(
            child: Text(
              title,
              style: TextStyle(
                fontSize: 12.sp,
                color: rgba(153, 153, 153, 1),
              ),
            ),
          ),
          Container(
            child: Text(
              value,
              style: TextStyle(
                fontSize: 14.sp,
                color: rgba(51, 51, 51, 1),
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
